$NG.AllReady(function (
  page,
  { useDataIndexChange, useUpdateRow, useValuesChange, useUpdateRows, useClick,useBeforeClick }
) {

  // 编辑页面逻辑
  const mstform = $NG.getCmpApi("p_form_employ_projbal");
  const grid1 = $NG.getCmpApi("p_form_employ_projbal_d");
  const grid2 = $NG.getCmpApi("p_form_employ_projbal_d1");

  // 设置默认值人民币和汇率
  if(page.oType == 'add'){
    mstform.getItem('u_total_payamt').setValue(0)
    mstform.getItem('u_htkp_amt').setValue(0)
    mstform.getItem('u_ht_apply_amt').setValue(0)
      $NG.updateState((updater)=>{
          updater.data.p_form_employ_projbal.setProps({
              phid_fcur:{
                  label:'人民币',
                  value:1
              },
              exchangerate:1
          })
      })
      // mstform.getItem('creator').setValue({
      //   value: $NG.getUser().userID,
      //   label:$NG.getUser().userName
      // })
      $NG.execServer("getEpmInfoByUserID", { phid: $NG.getUser().userID }, function (res) {
        const datas = JSON.parse(res.data)[0].extendObjects;
        console.log(datas);
        $NG.updateState((updater) => {
           //【注意这里的表名不能为控件ID，必须要是表名】
           updater.data.p_form_employ_projbal.setProps({
               creator: {
                 value: datas.fu_phid,
                 label: datas.hem_name,
              },
              u_app_dept: {
                 value: datas.dept_phid,
                 label: datas.dept_name,
              },
           //    u_zg_no: datas.hem_no,
           //    bill_name: datas.hem_name + year + "年" + month + "月工时填报",
           });
        });
     });
  }
  // 缓存存储过滤的工资表内容
  const salaryTable = {};
  // 缓存其他合同初始累计
  let _cntSalary = {};
  // 存储并设置表体对象
  const cntSalary = {
    _cnt_amt: 0,
    _cnt_sq_amt: 0,
    _cnt_kp_amt: 0,
    set cnt_amt(value) {
      this._cnt_amt = Number(value);
      setCntAmt(this._cnt_amt, this._cnt_sq_amt, this._cnt_kp_amt);
    },
    set cnt_sq_amt(value) {
      this._cnt_sq_amt = Number(value);
      setCntAmt(this._cnt_amt, this._cnt_sq_amt, this._cnt_kp_amt);
    },
    set cnt_kp_amt(value) {
      this._cnt_kp_amt = Number(value);
      setCntAmt(this._cnt_amt, this._cnt_sq_amt, this._cnt_kp_amt);
    },
  };
  $NG.execServer("getTkCnt", { phid: "8570000000000011" }, function (res) {
    console.log("测试", res);
  });
  cntMFilter();
  // 监听表格行变化
  useUpdateRow(({ args }) => {
    initSalary(args);
        const billnoSet = new Set();
      const nonDuplicateArgs = [];

  grid1.getRows().forEach((item) => {
      const billno = item.u_yg_billno;
      if (billno &&!billnoSet.has(billno)) {
          billnoSet.add(billno);
          nonDuplicateArgs.push(item);
      } else if (billno) {	
          $NG.alert("已存在当前应付单！");
      }
  grid1.clearRows().then(()=>{
      grid1.addRows([...nonDuplicateArgs])
  })
  grid1.refreshView()
  })
  }, "p_form_employ_projbal_d");
  // 监听支付比例
  useValuesChange(({ args }) => {
    console.log(`监听支付比例`, args);
    const dArr = grid1.getRows();
    dArr.forEach((item) => {
        item.u_zfbl = args[0].u_zf_bfb;
    });
    sum()
    grid1.refreshView();
  }, "p_form_employ_projbal.u_zf_bfb");
  useValuesChange(({ args }) => {
      getSuppyInfo()
    }, "p_form_employ_projbal.u_sk_dw");
  // /10.表体数据变化（增行、删行、引入）时，汇总计算至表头
  // useUpdateRow(({args})=>{
  //     const billnoSet = new Set();
  //     const nonDuplicateArgs = [];

  // grid1.getRows().forEach((item) => {
  //     const billno = item.u_yg_billno;
  //     if (billno &&!billnoSet.has(billno)) {
  //         billnoSet.add(billno);
  //         nonDuplicateArgs.push([...item]);
  //     } else if (billno) {	
  //         $NG.alert("已存在当前应付单！");
  //     }
  // },"p_form_employ_projbal_d");
  // grid1.clearRows().then(()=>{
  //     grid1.addRows([...nonDuplicateArgs])
  // })
  // grid1.refreshView()
  // })
  useUpdateRows(({ args }) => {
      const billnoSet = new Set();
  // 用于存储不重复数据项的数组
  
  
    console.log(`表体监听`, args);
    sum();
    grid1.refreshView()
    grid2.refreshView()
  }, "p_form_employ_projbal_d");
  //表体发票金额合计
  useUpdateRows(({ args }) => {
    sum();
    var sumAmt = 0;
    var u_yksje = 0;
    const rows = args[0];
    rows.forEach((items) => {
        sumAmt += (Number(items.u_invo_taxamt) || 0)
        u_yksje +=(Number(items.u_total_tax_amt) || 0)
      //汇总赋值
    });
    $NG.updateState((updater) => {
      updater.data.p_form_employ_projbal.setProps({
        u_bcfpje:sumAmt,
        u_yksje:u_yksje
      });
    });
  }, "p_form_employ_projbal_d1");
  // 监听项目发生变化
  useValuesChange(({ args }) => {
    getProjectInfo();
    cntMFilter();
    $NG.updateState((updater) => {
      updater.data.p_form_employ_projbal.setProps({
        u_cnt: {
          label: "",
          value: "",
        },
        u_cnt_no: "",
      });
    });
    console.log(`监听项目`, args[0]);
  }, "p_form_employ_projbal.phid_pc");

  useValuesChange(({ args }) => {
    console.log(`监听合同`, args);
    htlx()
    grid1.clearRows();
    getCntInfo();
    getSalaryTable();
    cntDFilter();
    allSalary();
    getYfInfo();
    initUserType();
    getCntYfbKpAmt()
    getZbdAmtByCnt()
  }, "p_form_employ_projbal.u_cnt");
  function htlx(params) {
    $NG.execServer(
      "searchHtlx",
      { phid: `'${mstform.getItem("u_cnt").getValue()}'` },
      function (res) {
          if(res.count ==0) return
          const datas = JSON.parse(res.data)[0].extendObjects;
        if (datas.htlx == '实施外包用工') {
          mstform.getItem('u_lylx').setValue('dx')
        }
        if (datas.htlx == '服务外包用工') {
          mstform.getItem('u_lylx').setValue('dx')
        }else{
          mstform.getItem('u_lylx').setValue('ht')
        }

      }
  );
  }
  function initUserType(_data) {
    $NG.execServer(
        "searchJfdw",
        { phid: `'${mstform.getItem("u_cnt").getValue()}'` },
        function (res) {
            if(res.count ==0) return
            const datas = JSON.parse(res.data)[0].extendObjects;
            console.log(`甲方：`, datas);
            //帮助字段赋值

            console.log(mstform.getItem("u_cnt").getValue());
          mstform.getItem('u_pay_org').setValue({
            value: datas.jfdw,
            label:datas.jfmc
          })
        }
    );

  }
  function sum() {
    const _row1 = grid1.getRows();
    const _row2 = grid2.getRows();
    let _count1 = 0;
    let _count1_1 = 0;
    let _count2 = 0;
    let _count2_1 = 0;
    let sumAmt = 0
    _row1.forEach((element) => {
      console.log(`调试支付比例`,element.u_zfbl);
      if (!element.u_zfbl) {
          element.u_zfbl = mstform.getItem("u_zf_bfb").getValue();
      }
      element.u_approve_amt = (Number(element.u_apply_amt) || 0) * (Number(element.u_zfbl) || 0)
      if (element.u_approve_amt) {
          sumAmt += parseFloat(element.u_approve_amt);
      }
      _count1 += Number(element.u_apply_amt);
      _count1_1 += Number(element.u_approve_amt);
      if (!element.u_zfbl) {
          element.u_zfbl = mstform.getItem("u_zf_bfb").getValue();
        }
    });
    _row2.forEach((element) => {
      _count2 += Number(element.u_invo_amt);
      _count2_1 += Number(element.u_invo_tax);
    });
    $NG.updateState((updater) => {
      console.log(_cntSalary, "测试");
      cntSalary.cnt_amt = (_count1_1 || 0) + _cntSalary.cnt_amt;
      cntSalary.cnt_sq_amt = (_count1 || 0) + _cntSalary.cnt_sq_amt;
      cntSalary.cnt_kp_amt = (_count2 || 0) + _cntSalary.cnt_kp_amt;
      updater.data.p_form_employ_projbal.setProps({
        u_bc_apply_amt: _count1,
        u_bcsqfksyje: _count1,
        u_approve_amt: _count1_1,

        u_yksje: _count2_1,
        u_apply_amt: sumAmt
      });
    });
    grid1.refreshView()
  }
  getProjectInfo();
  //获取项目信息
  function getProjectInfo() {
    console.log(`项目phid——pc`, mstform.getItem("phid_pc").getValue());
    if (!mstform.getItem("phid_pc").getValue()) return;
    $NG.execServer(
      "getPtInfoByPhid",
      { phid: mstform.getItem("phid_pc").getValue() },
      (res) => {
        const _data = JSON.parse(res.data)[0].extendObjects;
        console.log(`获取项目信息`, _data);
        $NG.updateState((updater) => {
          updater.data.p_form_employ_projbal.setProps({
            u_agreed_sts_dt: _data.start_date, //计划完工日期
            u_agreed_pcl_dt: _data.end_date, //计划竣工日期
            u_sqgw: {
              //售前顾问
              value: _data.user_sqgw_phid,
              label: _data.user_sqgw_name,
            },
            u_division: {
              //事业部or组织or分公司
              value: _data.org_phid,
              label: _data.org_name,
            },
            // 分公司
            u_fgs: {
              value: _data.org_phid,
              label: _data.org_name,
            },
            u_regional_center: {
              //区域中心
              value: _data.regional_center_phid,
              label: _data.regional_center_name,
            },
            u_product_line: {
              //产品线
              value: _data.midwife_phid,
              label: _data.midwife_name,
            },
            u_dept: {
              //部门
              value: _data.dept_phid,
              label: _data.dept_name,
            },
            u_pc_type: {
              //项目类型
              value: _data.type_phid,
              label: _data.type_name,
            },
            u_pc_no: _data.pc_no,
          });
        });
      }
    );
  }
  // 过滤函数
  function cntMFilter() {
    console.log(`开始过滤`);
    $NG.updateUI((updater, state) => {
      updater.fieldSetForm.p_form_employ_projbal.u_cnt.setProps({
        onBeforeOpen: async () => {
          var phid_pc = $NG
            .getCmpApi("p_form_employ_projbal")
            .getItem("phid_pc")
            .getValue();
          if (!phid_pc) {
            $NG.alert("请先选择项目");
            return false;
          } else {
            return true;
          }
        },
        ...(!!$NG
          .getCmpApi("p_form_employ_projbal")
          .getItem("phid_pc")
          .getValue() && {
          clientSqlFilter: {
            xm_no: $NG
              .getCmpApi("p_form_employ_projbal")
              .getItem("phid_pc")
              .getValue(),
          },
        }),
      });
    });
  }

  // 获取合同信息
  function getCntInfo() {
    $NG.execServer(
      "GetWbhtInfo",
      { phid: mstform.getItem("u_cnt").getValue() },
      function (res) {
        console.log(mstform.getItem("u_cnt").getValue(), res);
        if (res.count == 0) {
          return;
        }
        const datas = JSON.parse(res.data)[0].extendObjects;
        console.log(`合同：`, datas);
        //帮助字段赋值
        $NG.updateState((updater) => {
          updater.data.p_form_employ_projbal.setProps({
            u_cnt_no: datas.bill_no,
            u_cnt_amt: datas.amt,
            u_pq_company: {
              label: datas.wbgs_name,
              value: datas.wbgs,
            },
            u_sk_dw:{
              value:datas.wbgs,
              label:datas.wbgs_name
            }
          });
        });
        setTimeout(()=>{
          getSuppyInfo()
        },500)
      }
    );
  }
// 获取供应商银行信息
function getSuppyInfo(){
  const phid = mstform.getItem("u_sk_dw").getValue()
  if(!phid) return 
  $NG.execServer("getSuppyInfo", { phid }, (res) => {
      console.log(`查询供应商信息`,res);
      if(res.count == 0) return 
      const _data = JSON.parse(res.data)[0].extendObjects
      $NG.updateState((updater)=>{
          updater.data.p_form_employ_projbal.setProps({
              u_bank_no: _data.user_yhzh,
              u_rece_bank:{
                  label:_data.user_bank_name,
                  value:_data.bphid
              }
          })
      })
  })
}
  // 获取工资表
  function getSalaryTable() {
    $NG.execServer(
      "getSalaryTableInfo",
      { phid: mstform.getItem("u_cnt").getValue() },
      function (res) {
        console.log(`工资表响应数据`, res);
        if (res.count == 0) {
          return;
        }
        const _data = JSON.parse(res.data);
        console.log(`获取工资表`, _data);
        _data.forEach((item) => {
          const _d = item.extendObjects;
          salaryTable[_d.phid] = { ..._d };
        });
      }
    );
  }

  function cntDFilter() {
    const phid_pcc = $NG
      .getCmpApi("p_form_employ_projbal")
      .getItem("u_cnt")
      .getValue();
    if (!phid_pcc) {
      return;
    }
    $NG.updateUI((updater) => {
      console.log(`附表过滤`, updater);
      updater.editGrid.p_form_employ_projbal_d.u_yg_billno.setProps((p) => {
        console.log(`正在过滤`);
        return {
          ...p,
          editor: {
            ...p.editor,
            clientSqlFilter: {
              u_cnt_name: $NG
                .getCmpApi("p_form_employ_projbal")
                .getItem("u_cnt")
                .getValue(),
            },
          },
        };
      });
    });
  }

  // 监听d表体的时候赋值其他字段
function initSalary(arg) { 
  //禁用
  return      
    const _data = salaryTable[arg[0].u_yg_billno];
    if (!_data) {
      $NG.alert("找不到单据或单据选择不正确/空！");
    }
    console.log(_data, salaryTable[arg[0].u_yg_billno], salaryTable);
    arg[0].u_apply_amt_vat = _data.total_amt;
    arg[0].u_apply_amt = _data.total_amt;
    if (!arg[0].u_approve_amt && arg[0] !== 0) {
      arg[0].u_approve_amt = _data.total_amt;
    }

    grid1.refreshView();
  }
  // 获取合同累计金额
  function allSalary() {
      const u_cnt = mstform.getItem("u_cnt").getValue()
      if(!u_cnt) return 
    $NG.execServer("getAllYfdInfo", {u_cnt}, function (res) {
      if(res.count == 0) return
      const _data = JSON.parse(res.data)[0].extendObjects;
      console.log(_data);
      _cntSalary = { ..._data };
      Object.keys(_data).forEach((item) => {
        cntSalary[item] = _data[item];
      });
    });
  }
  // 设置主表合同累计金额字段
  function setCntAmt(_c1, _c2, _c3) {
      //禁用
      return
    console.log(_c1, _c2, _c3);
    $NG.updateState((updater) => {
      updater.data.p_form_employ_projbal.setProps({
        // 累计付款
        u_total_payamt: _c1,
        // 累计开票
        u_htkp_amt: _c2,
        // 累计申请
        u_ht_apply_amt: _c3,
      });
    });
  }
  // 获取款项信息
  function getYfInfo() {
    $NG.execServer(
      "getTkCnt",
      { phid: mstform.getItem("u_cnt").getValue() },
      function (res) {
          if(res.count == 0) return
        const _data = JSON.parse(res.data)[0].extendObjects;
        console.log(`获取款项信息`, _data);
        $NG.updateState((updater) => {
          updater.data.p_form_employ_projbal.setProps({
            u_kx_type: {
              label: _data.a_name,
              value: _data.a_phid,
            },
            u_zf_bfb: _data.a_zfbfb,
            u_zf_js: _data.a_jsjs,
          });
        });
      }
    );
  }
  //添加按钮
console.log(`===============================================`);
  const gridToolbar = $NG.getCmpApi("toolbar_p_form_employ_projbal_d1");
  // $NG.getCmpApi("toolbar_p_form_employ_projbal_d1").insert({
  //   id: "myadd",
  //   text: "发票引用",
  //   iconCls: "icon-New",
  // });
  //添加按钮
  $NG.getCmpApi("toolbar_p_form_employ_projbal_d1").insert({
    id: "sendBtn",
    text: "获取发票信息",
    iconCls: "icon-New",
  });

  const billno = $NG
  .getCmpApi("p_form_employ_projbal")
  .getItem("bill_no")
  .getValue();
   console.log("获取到数据", billno);

  async function getToken() {
    const token = await $NG.request.post({
      url: "https://sd.hisense.com/sd/Fi/sdToFi/fiIntegration/authenticationFi",
      header: {
        "Content-Type": "application/json",
      },
    });
    console.log("获取 token 成功:", token);
    return token;
  }

  async function getEventCode() {
    const eventCode = await $NG.request.post({
      url: "https://sd.hisense.com/sd/Fi/sdToFi/fiIntegration/getYGEventCode",
      // url: "https://inner-apisix.hisense.com/hisense/sd/Fi/sdToFi/fiIntegration/getYGEventCode?user_key=pxgy9hyt9udfgfcsbzizykw0xfqi6uk6",
      data: JSON.stringify({ bill_no: billno }),
      header: {
        "Content-Type": "application/json",
      },
    });
    console.log("获取 eventCode 成功:", eventCode);
    return eventCode;
  }

  useClick(async function ({ args }) {
    console.log("点击了获取发票信息按钮");
    const identifytype = billno; // 页面唯一标识（根据实际需求设置）
    const token = await getToken();
    const eventCode = await getEventCode();

    // 修正 WebSocket URL
    const socketUrl = "wss://fi.hisense.com/ierp/msgwatch/";

    // 初始化 WebSocket
    const socket = new WebSocket(
      `${socketUrl}?identifytype=${encodeURIComponent(
        identifytype
      )}&token=${encodeURIComponent(token)}&listenerType=RimWebSocketListener`
    );

    // WebSocket 打开事件
    socket.onopen = () => {
      console.log("WebSocket 连接已建立:", new Date());
      var url = "https://fi.hisense.com/ierp/";
      var viewfpUrl =
        url + "index.html?formId=rim_fpzs_main&eventCode=" + eventCode;
      var encodeUrl = encodeURIComponent(viewfpUrl, "utf-8");
      var requestUrl =
        url +
        "accessTokenLogin.do?encode=true&access_token=" +
        token +
        "&redirect=" +
        encodeUrl;
      window.open(requestUrl);
      socket.send("来自客户端的消息: " + location.href + " - " + new Date());
    };

    // WebSocket 收到消息事件
    socket.onmessage = (event) => {
      console.log("收到服务器消息:", event.data); // 输出服务器返回的消息
      const data = JSON.parse(event.data);
      const invoiceData = data.invoiceData;

      // 获取表体当前的所有行数据
      const existingRows = $NG.getCmpApi("p_form_employ_projbal_d1").getRows();

      // 创建一个Set，用于快速判断表体中是否存在某发票号
      const existingInvoiceNos = new Set(existingRows.map((row) => row.u_fphm));

      // 定义存储新数据的数组
      var gridArr = [];

      // 判断 invoiceData 是否存在，并获取长度
      const gridCount = invoiceData ? invoiceData.length : 0;
      if (gridCount > 0) {
        for (let i = 0; i < gridCount; i++) {
          const invoice = invoiceData[i];
          const invoice_item = invoice.items[0];

          // 判断发票号是否已存在于表体中
          if (existingInvoiceNos.has(invoice.invoiceNo)) {
            console.log(
              `发票号 ${invoice.invoiceNo} 已存在于表体中，跳过此条数据`
            );
            continue; // 跳过重复数据
          }

          // 如果发票号未重复，则加入到gridArr中
          var gridObj = {
            u_fp_type: invoice.invoiceType,
            u_serial_no: invoice.serialNo,
            u_fpdm: invoice.invoiceCode,
            u_invo_no: invoice.invoiceNo,
            u_invo_dt: invoice.invoiceDate,
            u_check_code: invoice.checkCode,
            u_saler_name: invoice.salerName,
            u_saler_taxno: invoice.salerTaxNo,
            u_saler_addressph: invoice.salerAddressPhone,
            u_saler_account: invoice.salerAccount,
            u_buyer_name: invoice.buyerName,
            u_buyer_taxno: invoice.buyerTaxNo,
            u_buyer_addressph: invoice.buyerAddressPhone,
            u_buyer_account: invoice.buyerAccount,
            u_invoice_amount: invoice.invoiceAmount,
            u_total_tax_amt: invoice.totalTaxAmount,
            u_invo_taxamt: invoice.totalAmount,
            
            u_machine_no: invoice.machineNo,
            u_drawer: invoice.drawer,
            u_reviewer: invoice.reviewer,
            u_payee: invoice.payee,
            u_invoice_sta: invoice.invoiceStatus,
            u_expend_sta: invoice.expendStatus,
            u_rk_dt: invoice.billCreateTime,
            u_check_sta: invoice.checkStatus,
            u_invalid_dt: invoice.invalidDate,
            u_type: invoice.type,
            u_ori_invoice_code: invoice.originalInvoiceCode,
            u_ori_invoice_no: invoice.originalInvoiceNo,
            u_download_url: invoice.downloadUrl,
            u_file_type: invoice.fileType,
            u_if_revise: invoice.isRevise,
            u_snapshot_url: invoice.snapshotUrl,
            u_errcode: invoice.errcode,
            u_description: invoice.description,
            u_validate_mes: invoice.validateMessage,
            u_msg: invoice.msg,
            u_name: invoice.name,
            u_config_type: invoice.configType,
            u_config: invoice.config,
            u_key: invoice.key,
            u_rate:invoice_item.taxRate,
          };
          gridArr.push(gridObj);
        }

        // 如果有新数据，插入到表体中
        if (gridArr.length > 0) {
          grid2.addRows(gridArr);
          console.log("新增的数据:", gridArr);
        } else {
          console.log("没有需要插入的新数据。");
        }
      } else {
        console.log("没有发票数据！");
      }
    };

    // WebSocket 关闭事件
    socket.onclose = (event) => {
      console.log("WebSocket 连接已关闭:", new Date());
      if (event.code !== 1000) {
        // 非正常关闭
        console.error(
          "连接异常关闭，错误代码:",
          event.code,
          "原因:",
          event.reason
        );
      }
    };

    // WebSocket 错误事件
    socket.onerror = (error) => {
      console.error("WebSocket 错误:", error);
    };

    // 防止内存泄漏，组件卸载时关闭 WebSocket
    return () => {
      if (socket.readyState === WebSocket.OPEN) {
        socket.close();
      }
    };
  }, "sendBtn");
  
      var tabPanel = document.getElementsByClassName("ant-tabs-tab"); //获取所有tab页元素
    tabPanel[1].addEventListener("click", function () {
        console.log("tab2被点击了");
        setTimeout(() => {
            if (page.oType == "add") {
                $NG.getCmpApi("toolbar_top").getItem("save").getRef().click(); //点击获取发票的时候，保存单据
                $NG.alert("请先保存主表数据");
                tabPanel[0].click();
            }
        }, 200);
    });

    // 获取累计值
    getCntYfbKpAmt()
    function getCntYfbKpAmt(){
      const cnt = mstform.getItem("u_cnt").getValue();
      if(!cnt) return;
      $NG.execServer("getCntYfbKpAmt",{cnt},function(result){
          if(result.count == 0) return 
          console.log(`获取累计值`,result);
          const _data = JSON.parse(result.data)[0].extendObjects
          $NG.updateState((updater)=>{
              updater.data.p_form_employ_projbal.setProps({
                  u_htkp_amt:(Number(_data.total_kpamt) || 0),
                  u_ht_apply_amt:(Number(_data.total_pfamt) || 0)
              })
          })
      })
    }
    getZbdAmtByCnt()
    function getZbdAmtByCnt(){
      const cnt = mstform.getItem("u_cnt").getValue();
      if(!cnt) return;
      $NG.execServer("getZbdAmtByCnt",{cnt},function(result){
          console.log(`获取支付单累计`,result);
          if(result.count == 0) return 
          const _data = JSON.parse(result.data)[0].extendObjects
          $NG.updateState((updater)=>{  
              updater.data.p_form_employ_projbal.setProps({
                  u_total_payamt:(Number(_data.amt) || 0)
              })
          })
      })
    }
});
